from django.utils.safestring import mark_safe
from django.urls import reverse
from stark.service.v1 import StarkHandler, get_choice_text, get_m2m_text, StarkModelForm
from web import models
from .base import PermissionHandler


class PrivateCustomerModelForm(StarkModelForm):
    class Meta:
        model = models.Customer
        exclude = ['consultant', ]  # 已登陆的，添加客户时不需要显示课程顾问这一选项


class PrivateCustomerHandler(PermissionHandler, StarkHandler):

    def display_record(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '跟进记录'
        url = reverse('stark:web_consultrecord_list', kwargs={'customer_id': obj.pk})
        return mark_safe('<a href="%s">查看跟进</a>' % url)

    def display_payment(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '缴费记录'
        url = reverse('stark:web_paymentrecord_list', kwargs={'customer_id': obj.pk})
        return mark_safe('<a href="%s">缴费记录</a>' % url)

    field_name_list = [StarkHandler.display_checkbox, 'name', get_choice_text('报名状态', 'status'),
                       get_m2m_text('咨询课程', 'course'), display_record, display_payment]

    def get_queryset(self, request, *args, **kwargs):
        current_user_id = request.session.get('current_user_id')
        # 获取当前登录用户的 私户信息
        return self.model_class.objects.filter(consultant__id=current_user_id)

    model_form_class = PrivateCustomerModelForm

    # 设置课程顾问默认值
    def save(self, request, form, is_update, *args, **kwargs):
        is_update = False
        if not is_update:
            consultant_id = request.session.get('current_user_id')
            form.instance.consultant_id = consultant_id
            form.save()

    # 批量添加到公户
    def multi_reverse_public(self, request):
        pk_list = request.POST.getlist('pk')
        # 去除 课程顾问的id 即可
        models.Customer.objects.filter(pk__in=pk_list).update(consultant_id=None)

    multi_reverse_public.text = '批量添加到公户'
    action_list = [multi_reverse_public, ]
